import { check } from 'meteor/check';
import { Channels } from '/imports/models/Channels';

/**
 * 按照频道分类获取频道列表
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('Explore.Channels.ByTypes', function(query, limit) {
  check(query['type.name'], String);

  let selector = {
    $or: [
      { 'policy.name': { $ne: 'private' } },
      { 'policy.apply': { $ne: false } }
    ]
  };

  if (query['type.name'] != 'all') {
    selector['type.name'] = query['type.name'];
  }

  Counts.publish(this, 'Explore.Channels.ByTypes.Counts', Channels.find(selector));

  return Channels.find(selector, {
    limit: limit,
    sort: {
      createdAt: -1
    }
  });
});

/**
 * 按照输入的内容查找频道
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('Explore.Channels.ByText', function(query, limit) {
  check(query.text, String);

  let selector = {};

  selector.$or = [
    { channelId: { $regex: new RegExp(query.text) } },
    { name: { $regex: new RegExp(query.text) } }
  ];

  Counts.publish(this, 'Explore.Channels.ByText.Counts', Channels.find(selector));

  return Channels.find(selector, {
    limit: limit,
    sort: {
      createdAt: -1
    }
  });
});

/**
 * 查询用户
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('Explore.Users.ByText', function(query, limit) {
  check(query.text, String);

  let selector = {};

  selector.username = { $regex: new RegExp(query.text) };

  Counts.publish(this, 'Explore.Users.ByText.Counts', Channels.find(selector));

  return Meteor.users.find(selector, {
    limit: limit
  });
});
